package com.fengxu.springclouod.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
*@Description 自定义日志的全局过滤器Filter
*@Author 风珝
*@Date 2021/1/17 10:57
*@Version 1.0.0
*/
//@Component
@Log4j2
public class MyLogGateWayFilter implements GlobalFilter, Ordered {


    // 过滤器的实现方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("******全局过滤器 -- {} *********", new Date());
        // ServerWebExchange 是web5.0以后的服务器对象
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if(uname == null){
            log.info("*****用户名为null,非法用户!******");
            // 设置403禁止的状态码
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        } else {
            log.info("*********用户名为{},验证通过*****",uname);
        }
        return chain.filter(exchange);
    }

    // 表示该过滤器的指定顺序，数字越小，优先级越高！
    @Override
    public int getOrder() {
        return 0;
    }
}
